package inventory.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import inventory.common.SexEnum;
import inventory.entity.Manager;
import inventory.entity.Role;
import inventory.entity.User;
import inventory.entity.po.ManagerPermissionRecordPo;
import inventory.entity.po.PermissionRecordPo;
import inventory.entity.po.UserPo;
import inventory.mappers.*;
import inventory.service.RepositoryService;
import inventory.service.UserService;
import inventory.utils.PasswordHelper;
import inventory.utils.UUIDUtils;
import inventory.utils.UserRoleUtil;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sxt
 * @since 2019-11-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPoMapper userPoMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RepositoryMapper repositoryMapper;
    @Autowired
    private PermissionRecordPoMapper permissionRecordPoMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ManagerPermissionRecordPoMapper managerPermissionRecordPoMapper;


    @Override
    public List<UserPo> queryUserPo(User user,String managerId) {
        String workId=user.getWorkId();
        String username=user.getUsername();
        List<UserPo> userPoList=null;

        List<String> roleIds = new ArrayList<>();
        List<String> resList=new ArrayList<>();
        resList.add(managerId);
        while (!resList.isEmpty()){
            resList=roleMapper.queryRoleIdByPid(resList);
            roleIds.addAll(resList);
        }
        boolean roleIdIsRight;

        String roleId;

        if(username!=null&&workId!=null){
            userPoList =userPoMapper.selectLikeUsernameAndWorkId(username,workId);
            if (userPoList == null){
                return null;
            }
            roleId  =userPoList.get(0).getRoleId();
          roleIdIsRight = (roleIds.contains(roleId) && !roleId.equals(managerId));
        }
        else if(username != null){
            userPoList = userPoMapper.selectLikeUsername(username);
            if (userPoList == null){
                return null;
            }
            roleId  =userPoList.get(0).getRoleId();
           roleIdIsRight = (roleIds.contains(roleId) && !roleId.equals(managerId));
        }
        else{
            userPoList = userPoMapper.selectLikeWorkId(workId);
            if (userPoList == null){
                return null;
            }
            roleId  =userPoList.get(0).getRoleId();
          roleIdIsRight = (roleIds.contains(roleId) && !roleId.equals(managerId));
        }
        if(roleIdIsRight) {
            return userPoList;
        }
        else {
            return null;
        }
    }

    @Override
    public Integer changeStatusById(String userId, String managerId, String status) {

            List<String> roleIds = new ArrayList<>();
            List<String> resList = new ArrayList<>();
            resList.add(managerId);
            while (!resList.isEmpty()) {
                resList = roleMapper.queryRoleIdByPid(resList);
                roleIds.addAll(resList);
            }
            String roleId = userMapper.queryRoleIdByUserId(userId);
            boolean isExist = roleIds.contains(roleId);
            if(isExist){
                userMapper.setStatus(userId,status);
                return 1;
            }
            else {
                return -1;
            }
    }

    @Override
    public User queryUserByWorkId(String workId) {
        User user = userMapper.queryUserByWorkId(workId);
        return user;
    }

    @Override
    public int  modifyById(User user,String workId,String managerId){
        String userId= userMapper.selectUserIdByWorkId(workId);
        List<String> roleIds = new ArrayList<>();
        List<String> resList=new ArrayList<>();
        resList.add(managerId);
        while (!resList.isEmpty()){
            resList=roleMapper.queryRoleIdByPid(resList);
            roleIds.addAll(resList);
        }


        String roleId=userMapper.queryRoleIdByUserId(userId);
        boolean roleIdIsRight = (roleIds.contains(roleId) && !roleId.equals(managerId));
        if(roleIdIsRight) {
            user.setUserId(userId);
            return userMapper.updateById(user);
        }
        else{
            return -1;
    }
    }


    @Override
    public int deleteUserById(String userId,String managerId) {
            try {
                List<String> roleIds = new ArrayList<>();
                List<String> resList=new ArrayList<>();
                resList.add(managerId);
                while (!resList.isEmpty()){
                    resList=roleMapper.queryRoleIdByPid(resList);
                    roleIds.addAll(resList);
                }
                String roleId = userMapper.queryRoleIdByUserId(userId);
                boolean isExist = roleIds.contains(roleId);
                int roleNum = userMapper.getRoleNumByRoleId(roleId);
                String stat= userMapper.getStatById(userId);
                if (!isExist||(roleNum<=1&&!stat.equals("0"))) {
                    return  -1;
                } else {
                    repositoryMapper.deleteByUserId(userId);
                    int primaryKey = userMapper.deleteById(userId);
                    return primaryKey;
                }
            }
            catch (Exception e){
                return -2;
            }

    }
    /**
     * @Description: 添加用户
     * @Param: User
     * @return: ResultData
     * @Author: jwx
     * @Date: 2019/11/20
     */
    @Override
    public int  addUser(User user,String managerId) {
        //获workId，判断是否存在
        try {
            Manager manager = managerMapper.selectById(managerId);

            String workId = user.getWorkId();
            String sex = user.getSex();
            String roleId = user.getRoleId();
            boolean isExist = userMapper.isWorkIdExist(workId);
            boolean sexIsRight = (sex.equals(SexEnum.FAMELE.getCode()) || sex.equals(SexEnum.MALE.getCode()));
            boolean roleIdIsRight;
            List<String> roleIds = new ArrayList<>();
            List<String> resList=new ArrayList<>();
            resList.add(managerId);

            while (!resList.isEmpty()){
                resList=roleMapper.queryRoleIdByPid(resList);
                roleIds.addAll(resList);
            }

            roleIdIsRight = (roleIds.contains(roleId)&&!roleId.equals(managerId));
            if (isExist) {
                return -1;//resultData.FAILD().setResultIns("workId已经存在了");
            } else if (!sexIsRight) {
                return -2;//resultData.FAILD().setResultIns("性别出错，只允许输入0和1");
            } else if (!roleIdIsRight) {
                return -3;// resultData.FAILD().setResultIns("roleId非法");
            } else if(manager.getTmpNum()>=manager.getMaxNum()){
                return -5;

            } else {
                //生成随机主键
                String userId = UUIDUtils.getId();
                user.setUserId(userId);
                //查询pId，设置PId
                String pid = roleMapper.queryPidByRoleId(roleId);
                user.setPid(pid);
                //添加用户到user表
                userMapper.addUser(user);
                return 1;
            }
        }
        catch (Exception e){
            e.printStackTrace();
            return -4;
        }
    }
                /**
                 *
                 * 为用户分配仓库
                 */
                /**
                //获取state
               String state = roleMapper.queryStateByRoleId(roleId);

                Repository repository= new Repository();
                //分配随机主键
                repository.setRepositoryId(UUIDUtils.getId());
                //设置用户
//                repository.setManagerId(userId);
//                //设置state
//                repository.setBelongingStatus(state);
                //设置仓库名
                repository.setRepositoryName(user.getUsername()+"的仓库");
                //添加到数据库
                repositoryMapper.insert(repository);
                 **/





    @Override
    public List<UserPo> queryAllUser(String managerId) {
        List<String> queryList=new ArrayList<String>();
        List<String> resList=new ArrayList<String>();
        resList.add(managerId);

        while (!resList.isEmpty()){
            resList=roleMapper.queryRoleIdByPid(resList);
            queryList.addAll(resList);
        }


        List<UserPo> list =  userPoMapper.queryAllUserByManager(queryList);
        return list;
    }

    @Override
    public List<User> queryUserByName(String username) {
        List<User> list = userMapper.queryUserByName(username);
        return list;
    }

    @Override
    public List<UserPo> selectUsersByRole(String roleId,String managerId) {
       List<UserPo> userPoList = userPoMapper.selectUserByRoleId(roleId);
        List<String> roleIds = new ArrayList<>();
        List<String> resList=new ArrayList<>();
        resList.add(managerId);

        while (!resList.isEmpty()){
            resList=roleMapper.queryRoleIdByPid(resList);
            roleIds.addAll(resList);
        }
        boolean roleIdIsRight = (roleIds.contains(roleId)&&!roleId.equals(managerId));
        if(roleIdIsRight){
            return userPoMapper.selectUserByRoleId(roleId);
        }
        else {
            return null;
        }
    }


    //---------------------------TTXXI START-------------------------------

    @Override
    public JSONObject login(String workId , String password, String type) {
        //初始化
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(workId,password);
        JSONObject jsonObject = new JSONObject();
        try {

            //登录，即身份校验，由通过Spring注入的MyRealm会自动校验输入的用户名和密码在数据库中是否有对应的值
            subject.login(token);

            Object principal = subject.getPrincipal();//如果成功登录，现在得到登录后存下的安全对象

            User user = userMapper.queryUserByWorkId(workId); //查询基本用户信息

            System.out.println(user);

            switch (type){
                case "0"://普通用户

                    if (principal instanceof User){
                        UserPo userPo = queryUserAllInfoByUserId(user.getUserId());//获取所有用户信息
                        userPo.setPassword(null);
                        userPo.setSalt(null);
                        jsonObject = JSONObject.fromObject(userPo);
                        jsonObject.put("signIn", userPo.getSignIn().getTime());//设置时间为long
                        Manager queryManagerByUserId = queryManagerByUserId(userPo.getUserId());

                        //查询对应市级
                        Role tempRole = new Role();
                        tempRole.setPid(queryManagerByUserId.getManagerId());
                        Role role = roleMapper.selectOne(tempRole);
                        jsonObject.put("managerId", queryManagerByUserId.getManagerId());
                        jsonObject.put("cityRoleId", role.getRoleId());
                        break;
                    }else {
                        return null;
                    }



                case "1"://管理员
                    if (principal instanceof Manager){
                        Manager tempManager = new Manager();
                        tempManager.setWorkId(workId);
                        Manager manager = managerMapper.selectOne(tempManager);
                        manager.setPassword(null);
                        manager.setSalt(null);
                        jsonObject = JSONObject.fromObject(manager);
                        jsonObject.put("permissionRecordPoList", managerPermissionRecordPoMapper.selectList(new EntityWrapper<ManagerPermissionRecordPo>().eq("manager_id", manager.getManagerId())));
                        jsonObject.put("timeLimit", manager.getTimeLimit().getTime());//设置时间为long
                        break;
                    }else{
                        return null;
                    }

                default:
                    jsonObject.put("msg", "type类型有误");
                    return jsonObject;

            }

            jsonObject.put("sessionId", subject.getSession().getId());//添加sessionId


        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

        return jsonObject;
    }

    @Override
    public UserPo queryUserAllInfoByUserId(String userId) {
        UserPo userPo ;

        userPo = userPoMapper.selectById(userId);

        //判断用户是个人还是市级区级，为下面查询仓库做准备
        Map<String,Object> map = new HashMap<>();
        map.put("user_id", userId);
        UserRoleUtil.judeUser(map);

        if (userPo != null) {
            userPo.setRepositoryList( repositoryMapper.selectByMap(map) );
            userPo.setPermissionRecordPoList( permissionRecordPoMapper.selectList(new EntityWrapper<PermissionRecordPo>().eq("user_id", userId)) );
        }

        return userPo;
    }

    @Override
    public boolean addManager(Manager manager) {
        manager.setManagerId(UUIDUtils.getId());
        manager.setPid("superManager");
        manager.setTmpNum(0L);
        PasswordHelper.encryptPassword(manager);
        Integer insert = managerMapper.insert(manager);
        return insert == 1;
    }

    @Override
    public Manager queryManagerByUserId(String userId) {
        //先查询到对应userid的人 信息
        UserPo userPo = userPoMapper.selectById(userId);
        Role role = roleMapper.selectById(userPo.getRoleId());

        //查询他的上级
        while (true){
            Role temp = roleMapper.selectById(role.getPid());
            if (temp!=null){
                role = temp;
            }else {
                break;
            }
        }

        return managerMapper.selectById(role.getPid());
    }

    @Override
    public boolean isSameManager(String userId1, String userId2) {
        Manager manager1 = queryManagerByUserId(userId1);
        Manager manager2 = queryManagerByUserId(userId2);
        return manager1.getManagerId().equals(manager2.getManagerId());
    }




    //---------------------------TTXXI END-------------------------------


    //---------------------------rhq start-------------------------------
    @Override
    public UserPo queryUserPoByUserId(String userId) {
        UserPo userPo = userPoMapper.queryUserPoByUserId(userId);
        return userPo;
    }

    //---------------------------rhq end-------------------------------


}
